import { embeddingService, AliyunEmbeddingService } from './aliyunEmbedding';
import { chatService, AliyunChatService } from './aliyunChat';

// 知识库条目接口
export interface KnowledgeItem {
  id: string;
  title: string;
  content: string;
  category?: string;
  tags?: string[];
  embedding?: number[];
  createdAt: Date;
  updatedAt: Date;
}

// 知识库搜索结果接口
export interface SearchResult {
  item: KnowledgeItem;
  similarity: number;
  score: number;
}

// 知识库管理类
export class KnowledgeBaseManager {
  private items: Map<string, KnowledgeItem> = new Map();
  private embeddingService: AliyunEmbeddingService;
  private chatService: AliyunChatService;

  constructor(
    embeddingServiceInstance?: AliyunEmbeddingService,
    chatServiceInstance?: AliyunChatService
  ) {
    this.embeddingService = embeddingServiceInstance || embeddingService;
    this.chatService = chatServiceInstance || chatService;
  }

  /**
   * 添加知识库条目
   * @param item 知识库条目
   * @param generateEmbedding 是否生成embedding向量
   */
  async addItem(
    item: Omit<KnowledgeItem, 'id' | 'embedding' | 'createdAt' | 'updatedAt'>,
    generateEmbedding: boolean = true
  ): Promise<string> {
    const id = this.generateId();
    const now = new Date();
    
    const knowledgeItem: KnowledgeItem = {
      ...item,
      id,
      createdAt: now,
      updatedAt: now
    };

    // 生成embedding向量
    if (generateEmbedding) {
      try {
        const embedding = await this.embeddingService.generateEmbedding(item.content);
        knowledgeItem.embedding = embedding;
      } catch (error) {
        console.warn(`为条目 ${id} 生成embedding失败:`, error);
      }
    }

    this.items.set(id, knowledgeItem);
    return id;
  }

  /**
   * 批量添加知识库条目
   * @param items 知识库条目数组
   * @param generateEmbeddings 是否生成embedding向量
   */
  async addItems(
    items: Array<Omit<KnowledgeItem, 'id' | 'embedding' | 'createdAt' | 'updatedAt'>>,
    generateEmbeddings: boolean = true
  ): Promise<string[]> {
    const ids: string[] = [];
    
    if (generateEmbeddings) {
      // 批量生成embeddings
      const contents = items.map(item => item.content);
      const embeddings = await this.embeddingService.generateEmbeddings(contents);
      
      for (let i = 0; i < items.length; i++) {
        const id = this.generateId();
        const now = new Date();
        
        const knowledgeItem: KnowledgeItem = {
          ...items[i],
          id,
          embedding: embeddings[i],
          createdAt: now,
          updatedAt: now
        };
        
        this.items.set(id, knowledgeItem);
        ids.push(id);
      }
    } else {
      // 逐个添加
      for (const item of items) {
        const id = await this.addItem(item, false);
        ids.push(id);
      }
    }
    
    return ids;
  }

  /**
   * 更新知识库条目
   * @param id 条目ID
   * @param updates 更新内容
   * @param regenerateEmbedding 是否重新生成embedding
   */
  async updateItem(
    id: string,
    updates: Partial<Omit<KnowledgeItem, 'id' | 'createdAt' | 'updatedAt'>>,
    regenerateEmbedding: boolean = true
  ): Promise<boolean> {
    const item = this.items.get(id);
    if (!item) {
      return false;
    }

    const updatedItem: KnowledgeItem = {
      ...item,
      ...updates,
      updatedAt: new Date()
    };

    // 如果内容更新了，重新生成embedding
    if (updates.content && regenerateEmbedding) {
      try {
        const embedding = await this.embeddingService.generateEmbedding(updates.content);
        updatedItem.embedding = embedding;
      } catch (error) {
        console.warn(`为条目 ${id} 重新生成embedding失败:`, error);
      }
    }

    this.items.set(id, updatedItem);
    return true;
  }

  /**
   * 删除知识库条目
   * @param id 条目ID
   */
  deleteItem(id: string): boolean {
    return this.items.delete(id);
  }

  /**
   * 获取知识库条目
   * @param id 条目ID
   */
  getItem(id: string): KnowledgeItem | undefined {
    return this.items.get(id);
  }

  /**
   * 获取所有知识库条目
   */
  getAllItems(): KnowledgeItem[] {
    return Array.from(this.items.values());
  }

  /**
   * 搜索知识库
   * @param query 查询文本
   * @param topK 返回前K个结果
   * @param minSimilarity 最小相似度阈值
   */
  async search(
    query: string,
    topK: number = 5,
    minSimilarity: number = 0.7
  ): Promise<SearchResult[]> {
    const items = this.getAllItems();
    const itemsWithEmbedding = items.filter(item => item.embedding);
    
    if (itemsWithEmbedding.length === 0) {
      return [];
    }

    try {
      // 生成查询的embedding
      const queryEmbedding = await this.embeddingService.generateEmbedding(query);
      
      // 计算相似度
      const results: SearchResult[] = itemsWithEmbedding.map(item => {
        const similarity = AliyunEmbeddingService.cosineSimilarity(
          queryEmbedding,
          item.embedding!
        );
        return {
          item,
          similarity,
          score: similarity
        };
      });

      // 过滤和排序
      return results
        .filter(result => result.similarity >= minSimilarity)
        .sort((a, b) => b.similarity - a.similarity)
        .slice(0, topK);
    } catch (error) {
      console.error('搜索知识库失败:', error);
      return [];
    }
  }

  /**
   * 智能客服回复
   * @param userMessage 用户消息
   * @param topK 搜索前K个相关知识
   * @param minSimilarity 最小相似度阈值
   * @param systemPrompt 系统提示词
   */
  async intelligentReply(
    userMessage: string,
    topK: number = 3,
    minSimilarity: number = 0.7,
    systemPrompt?: string
  ): Promise<string> {
    try {
      // 搜索相关知识
      const searchResults = await this.search(userMessage, topK, minSimilarity);
      
      // 提取相关知识内容
      const knowledgeContent = searchResults.map(result => 
        `标题: ${result.item.title}\n内容: ${result.item.content}`
      );

      // 生成智能回复
      return await this.chatService.intelligentReply(
        userMessage,
        knowledgeContent,
        systemPrompt
      );
    } catch (error) {
      console.error('智能回复失败:', error);
      return '抱歉，我现在无法回答您的问题，请稍后再试。';
    }
  }

  /**
   * 导出知识库
   */
  export(): KnowledgeItem[] {
    return this.getAllItems();
  }

  /**
   * 导入知识库
   * @param items 知识库条目数组
   * @param clearExisting 是否清除现有数据
   */
  async import(
    items: KnowledgeItem[],
    clearExisting: boolean = false
  ): Promise<void> {
    if (clearExisting) {
      this.items.clear();
    }

    // 重新生成embeddings
    const contents = items.map(item => item.content);
    const embeddings = await this.embeddingService.generateEmbeddings(contents);

    for (let i = 0; i < items.length; i++) {
      const item = items[i];
      const updatedItem: KnowledgeItem = {
        ...item,
        embedding: embeddings[i],
        updatedAt: new Date()
      };
      this.items.set(item.id, updatedItem);
    }
  }

  /**
   * 获取知识库统计信息
   */
  getStats(): {
    totalItems: number;
    itemsWithEmbedding: number;
    categories: string[];
    tags: string[];
  } {
    const items = this.getAllItems();
    const categories = [...new Set(items.map(item => item.category).filter(Boolean))];
    const tags = [...new Set(items.flatMap(item => item.tags || []))];
    
    return {
      totalItems: items.length,
      itemsWithEmbedding: items.filter(item => item.embedding).length,
      categories,
      tags
    };
  }

  /**
   * 生成唯一ID
   */
  private generateId(): string {
    return Date.now().toString(36) + Math.random().toString(36).substr(2);
  }
}

// 创建默认的知识库管理器实例
export const knowledgeBaseManager = new KnowledgeBaseManager(); 